package api

import (
	"banke/utile"
	"net/http"

	"github.com/gin-gonic/gin"
)

var loginData struct {
	Username string `json:"username"`
	Password string `json:"password"`
}

func getUserInfo(c *gin.Context) {
	userID := c.Query("id")  // 从查询参数中获取用户 ID
	if userID == "" {
		c.JSON(http.StatusBadRequest, gin.H{"status": 0, "error": "User ID is required"})
		return
	}

	userInfo, err := utile.FindUserByID(userID)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"status": 0, "error": err.Error()})
		return
	}

	if userInfo == nil {
		c.JSON(http.StatusNotFound, gin.H{"status": 0, "error": "User not found"})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"status":   1,
		"userInfo": userInfo,
		"message":  "User information retrieved successfully",
	})
}

func userLogin(c *gin.Context) {
	if err := c.BindJSON(&loginData); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"status": 0,
			"error":  err.Error(),
		})
		return
	}

	userInfo, err := utile.FindUser(loginData.Username)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"status":  0,
			"code":    0,
			"message": err.Error(),
		})
		return
	}

	if userInfo.Password != loginData.Password {
		c.JSON(http.StatusOK, gin.H{
			"status":  0,
			"code":    0,
			"message": "password error",
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"status":   1,
		"code":     1,
		"message":  "login successful",
		"userInfo": userInfo,
	})
}

func registerUser(c *gin.Context) {
	var newUser utile.UserInfo
	if err := c.BindJSON(&newUser); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"status": 0,
			"error":  err.Error(),
		})
		return
	}

	existingUser, err := utile.FindUser(newUser.Username)
	if err == nil && existingUser != nil {
		c.JSON(http.StatusConflict, gin.H{
			"status": 0,
			"error":  "Username already exists",
		})
		return
	}

	if err := utile.CreateUser(&newUser); err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"status": 0,
			"error":  err.Error(),
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"status":  1,
		"message": "User registered successfully",
	})
}
